package com.xkdx.guangguang.fragment.user;

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.xkdx.caipiao.R;
import com.xkdx.guangguang.ManagerActivity;
import com.xkdx.guangguang.fragment.BaseFragment;
import com.xkdx.guangguang.fragment.user.UserResetPwdCommitModule.CommitVertifyCodeInfo;
import com.xkdx.guangguang.fragment.user.UserResetPwdModule.RequsetVertifyCodeInfo;
import com.xkdx.guangguang.module.network.AbsModule;
import com.xkdx.guangguang.module.util.ErrorModule;

public class UserResetPwdFragment extends BaseFragment implements
		OnClickListener {

	private View view;
	private Button resetpwd_back, vertifycode, commit;
	private EditText phoneNum, inputcode, newpassword;

	private static String getedVertifyCode;
	private ProgressDialog resetPwdDialog;
	private UserResetPwdAction resetPwdAction;
	private UserResetPwdModule resetPwdModule;
	private UserResetPwdPresenter resetPwdPresenter;
	private RequsetVertifyCodeInfo getVertifyCode;
	private CommitVertifyCodeInfo commitCode;
	private UserResetPwdCommitAction resetPwdCommitAction;
	private UserResetPwdCommitModule resetPwdCommitModule;
	private UserResetPwdCommitPresenter resetPwdCommitPresenter;
	private static final int TYPE_ONE = 1;
	private static final int TYPE_TWO = 2;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.user_reset_password, container, false);
		findViews();
		return view;
	}

	private void findViews() {

		resetpwd_back = (Button) view.findViewById(R.id.user_resetpwd_back);
		vertifycode = (Button) view
				.findViewById(R.id.user_resetpwd_vertifycode);
		phoneNum = (EditText) view.findViewById(R.id.user_resetpwd_phone);


		inputcode = (EditText) view.findViewById(R.id.user_resetpwd_inputcode);
		newpassword = (EditText) view.findViewById(R.id.user_resetpwd_newpwd);
		commit = (Button) view.findViewById(R.id.user_resetpwd_commit);
		resetpwd_back.setOnClickListener(this);
		vertifycode.setOnClickListener(this);
		commit.setOnClickListener(this);
		resetPwdDialog = new ProgressDialog(getActivity());
		resetPwdDialog.setMessage("登陆验证中,请耐心等待...");
		resetPwdDialog.setCancelable(true);
		resetPwdDialog.setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				getActivity().finish();

			}
		});

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.user_resetpwd_back: // 返回按钮
			getedVertifyCode = "";
			FragmentManager fm = getFragmentManager();
			fm.popBackStack();
			break;

		case R.id.user_resetpwd_vertifycode: // 获取验证码
			InputMethodManager im = (InputMethodManager) getActivity()
					.getSystemService(Context.INPUT_METHOD_SERVICE);
			if (im.isActive()) {
				im.hideSoftInputFromWindow(phoneNum.getWindowToken(), 0);
			}
			if (!CheckPhomeNum()) {
				return;
			} else {

				showLoading(TYPE_ONE);
			}
			break;
		case R.id.user_resetpwd_commit: // 提交验证码和新密码(重置密码 )
			if (!isCommitAvilidate()) {
				return;
			} else {
				showLoading(TYPE_TWO);
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 判断提交按钮相关是否合法
	 * 
	 * @return true合法 , false不合法
	 */
	private boolean isCommitAvilidate() {

		String inputvertifycode = inputcode.getText().toString().trim();
		String reinputpasswore = newpassword.getText().toString().trim();
		if (TextUtils.isEmpty(inputvertifycode)) {
			inputcode.setFocusable(true);
			inputcode.setFocusableInTouchMode(true);
			inputcode.requestFocus();
			Toast.makeText(getActivity(), "验证码不能为空...", Toast.LENGTH_SHORT)
					.show();
			return false;
		}
		if (TextUtils.isEmpty(reinputpasswore)) {
			newpassword.setFocusable(true);
			newpassword.setFocusableInTouchMode(true);
			newpassword.requestFocus();
			Toast.makeText(getActivity(), "重置的密码不能为空...", Toast.LENGTH_SHORT)
					.show();
			return false;
		} else if (!(inputvertifycode.equals(getedVertifyCode))) {
			inputcode.setFocusable(true);
			inputcode.setFocusableInTouchMode(true);
			inputcode.requestFocus();
			Toast.makeText(getActivity(), "输入的验证码不正确,请重新输入", 0).show();
			return false;

		}
		return true;
	}

	private void showLoading(int type) {
		if (type == TYPE_ONE) {
			resetPwdAction = new UserResetPwdAction(phoneNum.getText()
					.toString().trim());
			resetPwdModule = new UserResetPwdModule();
			resetPwdPresenter = new UserResetPwdPresenter(this);
			((ManagerActivity) getActivity()).addCurrentTask(resetPwdPresenter);
			resetPwdPresenter.setActitons(resetPwdAction);
			resetPwdPresenter.setModule(resetPwdModule);
			resetPwdPresenter.execute();
		} else {
			resetPwdCommitAction = new UserResetPwdCommitAction(phoneNum.getText()
					.toString(),
					newpassword.getText().toString().trim());
			resetPwdCommitModule = new UserResetPwdCommitModule();
			resetPwdCommitPresenter = new UserResetPwdCommitPresenter(this);
			((ManagerActivity) getActivity())
					.addCurrentTask(resetPwdCommitPresenter);
			resetPwdCommitPresenter.setActitons(resetPwdCommitAction);
			resetPwdCommitPresenter.setModule(resetPwdCommitModule);
			resetPwdCommitPresenter.execute();
		}
		resetPwdDialog.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				if (resetPwdCommitPresenter != null) {
					resetPwdCommitPresenter.cancel(true);
				}
				getFragmentManager().popBackStack();

			}
		});
		resetPwdDialog.show();
		
	}

	// 验证输入的手机号
	private boolean CheckPhomeNum() {
		boolean isAvilidate = true;

		String str = phoneNum.getText().toString().trim();
		if (TextUtils.isEmpty(str)) {
			if (getActivity() != null) {
				phoneNum.setFocusable(true);
				phoneNum.setFocusableInTouchMode(true);
				phoneNum.requestFocus();
				Toast.makeText(getActivity(), "获取验证码的手机号不能为空...", 0).show();
			}
			isAvilidate = false;
		} else if (!isMatchMobile(str)) {
			if (getActivity() != null) {
				phoneNum.setFocusable(true);
				phoneNum.setFocusableInTouchMode(true);
				phoneNum.requestFocus();
				Toast.makeText(getActivity(), "请输入正确格式的手机号码...", 0).show();
			}
			isAvilidate = false;
		}
		return isAvilidate;
	}
	/**
	 * 匹配正确格式的手机号
	 * 
	 * @param mobiles
	 * @return
	 */
	public static boolean isMatchMobile(String mobiles) {
		Pattern p = Pattern
				.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

	public void showLoaded(HashMap<String, AbsModule> msg) {
		if (resetPwdDialog != null && resetPwdDialog.isShowing()) {
			resetPwdDialog.dismiss();
		}

		if (msg.containsKey("0")) {
			getVertifyCode = ((UserResetPwdModule) msg.get("0")).getVertifyCode;
			if (getVertifyCode != null
					&& getVertifyCode.getStatus().equals("Success")) {
				getedVertifyCode = getVertifyCode.getCheckSn();
				Toast.makeText(getActivity(), "正在发送验证码，请等待...", 0).show();  

			} else {
				Toast.makeText(getActivity(), getVertifyCode.getMessage(), 0)
						.show();
			}
		} else {
			Toast.makeText(getActivity(),
					((ErrorModule) msg.get("1")).errorMessage,
					Toast.LENGTH_SHORT).show();
		}

	}

	public void showLoadedCommit(HashMap<String, AbsModule> msg) {
		if (resetPwdDialog != null && resetPwdDialog.isShowing()) {
			resetPwdDialog.dismiss();
		}

		if (msg.containsKey("0")) {
			commitCode = ((UserResetPwdCommitModule) msg.get("0")).commitCode;
			if (commitCode != null && commitCode.getStatus().equals("Success")) {
				Toast.makeText(getActivity(), "密码重置成功...", 0).show();
				getFragmentManager().popBackStack();
			} else {
				Toast.makeText(getActivity(), commitCode.getMessage(), 0)
						.show();
			}
		} else {
			Toast.makeText(getActivity(),
					((ErrorModule) msg.get("1")).errorMessage,
					Toast.LENGTH_SHORT).show();
		}

	}

	@Override
	public void showClick(HashMap<String, AbsModule> map) {
		// TODO Auto-generated method stub

	}

	@Override
	public void showLoadMore(HashMap<String, AbsModule> map) {
		// TODO Auto-generated method stub

	}

	@Override
	public void showLoading() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void findView() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setOnClick() {
		// TODO Auto-generated method stub
		
	}

}
